﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.Serialization;
using SysTrayRadio.Properties;

namespace SysTrayRadio
{
    public partial class Main : Form
    {
        readonly WMPLib.WindowsMediaPlayerClass _player = new WMPLib.WindowsMediaPlayerClass();
        ParameterizedThreadStart _playThread;
        Thread _t;


        readonly NotifyIcon _netradioIcon = new NotifyIcon();
        readonly ContextMenuStrip _playlist = new ContextMenuStrip();

        readonly List<Station> _stations = new List<Station>();

        public Main()
        {
            _stations = LoadPlayList();
            InitializeApp();
            InitializeComponent();
          
        }

        private void InitializeApp()
        {
            ShowInTaskbar = false;
            WindowState = FormWindowState.Minimized;

           _netradioIcon.Visible = true;
            _netradioIcon.ContextMenuStrip = _playlist;
            _netradioIcon.Icon = Resources.control_stop;

            _playlist.Items.Add(BuildSetupMenu());
            _playlist.Items.Add(new ToolStripSeparator());

            AddStationsToList();
            
            _netradioIcon.MouseClick += NetradioIconMouseClick;

            ShowSetup(null, null);
        }

        private ToolStripMenuItem BuildSetupMenu()
        {
            var item = new ToolStripMenuItem("Settings", Resources.application_task, null,"");
            foreach (var station in _stations)
            {
                var s = new ToolStripMenuItem(station.Name, null, null, station.Url)
                            {
                                Checked = station.IsActive,
                                CheckOnClick = true,
                            };

                s.CheckedChanged += SetupMenuCheckedChanged;

                item.DropDownItems.Add(s);
            }

            return item;
        }

        private void SetupMenuCheckedChanged(object sender, System.EventArgs e)
        {

        }
    


        static void ShowSetup(object sender, EventArgs e)
        {
            var setup = new Setup();
            setup.ShowDialog();
        }

        void NetradioIconMouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && Settings.Default.Playing)
            {
                _player.stop();
                _netradioIcon.Text = Resources.Main_NetradioIconMouseClick_SysTray_NetRadio;
                foreach (ToolStripItem item in _playlist.Items)
                {
                    item.Image = null;
                }
                _netradioIcon.Icon = Resources.control_stop;
                Settings.Default.Playing = false;
                Settings.Default.Save();
            }
            else if (e.Button == MouseButtons.Left)
            {
                PlayLastKnowRadio();
            }
        }

        private void PlayLastKnowRadio()
        {
            if (Settings.Default.LastPlayedUrl.Length > 0)
            {
                foreach (var item in _playlist.Items.Cast<ToolStripItem>().Where(item => item.Text == Settings.Default.LastPlayedName && item.Name == Settings.Default.LastPlayedUrl))
                {
                    StartPlayThread(item);
                    break;
                }
            }
            else if (_playlist.Items.Count > 0)
            {
                StartPlayThread(_playlist.Items[0]);
            }
        }

        void PlaylistItemClicked(object sender, EventArgs e)
        {
            StartPlayThread((ToolStripItem) sender);
        }

        private void StartPlayThread(ToolStripItem toolStripItem)
        {
            _playThread = PlayStream;

            _t = new Thread(_playThread) {IsBackground = true};
            _netradioIcon.Icon = Resources.control_play;

            foreach (var item in _playlist.Items.Cast<ToolStripItem>().Where(item => item.Name != string.Empty))
            {
                item.Image = null;
            }

            toolStripItem.Image = Resources.music;
            Settings.Default.LastPlayedName = toolStripItem.Text;
            Settings.Default.LastPlayedUrl = toolStripItem.Name;
            Settings.Default.Playing = true;
            Settings.Default.Save();

            _netradioIcon.Text = Resources.Main_StartPlayThread_Listining_to_ + toolStripItem.Text;
            _t.Start(toolStripItem.Name);
        }

        public void PlayStream(Object url)
        {
            try
            {
                _player.URL = url.ToString();
                _player.controls.play();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private List<Station> LoadPlayList()
        {
            using (var fs = new FileStream(@"PlayList.xml", FileMode.Open, FileAccess.Read))
            {
                var x = new XmlSerializer(_stations.GetType());
                var stationlist = (List<Station>)x.Deserialize(fs);

               

                return stationlist;
            }
        }

        private void AddStationsToList()
        {
            foreach (var station in _stations.Where(station => station.IsActive))
            {
                _playlist.Items.Add(new ToolStripMenuItem(station.Name, null, PlaylistItemClicked, station.Url));
            }
        }
    }
}
